package problems.practice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 692. 前K个高频单词
 * https://leetcode.cn/problems/top-k-frequent-words/
 *
 * @author habitplus
 * @since 2022/8/14 9:24
 */
public class T692 {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> cntMap = new HashMap<>();
        List<String> list = new ArrayList<>();
        int cnt;
        for (String w : words) {
            cnt = cntMap.getOrDefault(w, 0);
            if (cnt == 0)
                list.add(w);
            cntMap.put(w, cnt + 1);
        }

        list.sort((s1, s2) -> {
            int cnt1 = cntMap.getOrDefault(s1, 0);
            int cnt2 = cntMap.getOrDefault(s2, 0);
            if (cnt1 != cnt2)
                return cnt2 - cnt1;
            else
                return s1.compareTo(s2);
        });

        return list.subList(0, k);
    }
}
